#!/usr/bin/env python

from BaseHTTPServer import BaseHTTPRequestHandler
from subprocess import call
import datetime

class TodoHandler(BaseHTTPRequestHandler):

    # projHome = {
    #   "/workflow" :"/home/appbricks/ab-workflow/startup-code.sh",
    #   "/system"   :"/home/appbricks/gd-system/startup-code.sh",
    #   "/security" :"/home/appbricks/ab-security/startup-code.sh"
    # }

    logFile = "/home/wzq/workspace/python-learn/http_server/log"

    projHome = {
      "/a1" :"/home/wzq/workspace/python-learn/http_server/a1.sh",
      "/a2" :"/home/wzq/workspace/python-learn/http_server/a2.sh",
      "/a3" :"/home/wzq/workspace/python-learn/http_server/a3.sh"
    }

    def do_POST(self):
        #
        self.send_response(200)
        self.end_headers()
        self.wfile.write("ok")
        #
        print "path=", self.path
        length = int(self.headers['content-length'])
        body = self.rfile.read(length)
        print "length=", length
        print "body=", body
        self.upateProj(self.path, body)

    def upateProj(self, path, body):
        script = TodoHandler.projHome.get(path)
        if script:
            # log
            logFile = open(TodoHandler.logFile, 'a')
            logFile.write("\n\n")
            logFile.write(datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S"))
            logFile.write("\n")
            logFile.write(body)
            logFile.close()

            # execute this script
            print "script = ", script
            call(["/bin/bash",script])
        else:
            print "script not found, path = ", path


if __name__ == '__main__':
    # Start a simple server, and loop forever
    from BaseHTTPServer import HTTPServer
    server = HTTPServer(('', 12345), TodoHandler)
    print("Starting server, use <Ctrl-C> to stop")
    server.serve_forever()